//
//  RegisteredViewController.m
//  PrintPort
//
//  Created by 华谕 on 2017/11/13.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "RegisteredViewController.h"
#import "CloseAreaViewController.h"
#import "AddressModel.h"

static int seconds = 60;//计时60s
@interface RegisteredViewController ()<UIScrollViewDelegate,UITextFieldDelegate>
{
    UIScrollView *scrollview;
    UITextField *phoneField;
    UITextField *passwordField;
    UITextField *codeField;
    UITextField *invitField;
    UIButton *codeBtn;
    NSTimer *timer;
    UILabel *cityLab;
}
@property (nonatomic, strong)NSString *privceStr;
@property (nonatomic, strong)NSString *cityStr;
@property (nonatomic, strong)AddressModel *provceModel;
@property (nonatomic, strong)AddressModel *cityModel;
@property (nonatomic, strong)AddressModel *areasModel;
@property (nonatomic, strong)NSString *keyStr;

@end

@implementation RegisteredViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jianpanhuishou:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

//    [timer invalidate];
    [self renewTimer];
    timer = nil;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _keyStr = @"";
    [self creatUI];
    [self requestFindByKey];
    
}

- (void)creatUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"注册";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(receiveRecord)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT)];
    scrollview.backgroundColor = [UIColor whiteColor];
    scrollview.delegate = self;
    scrollview.contentOffset = CGPointMake(0, 0);
    scrollview.pagingEnabled = NO;
    scrollview.contentSize = CGSizeMake(SCREEN_WIDTH, 550*displaywidth);
    [self.view addSubview:scrollview];
    UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollTap:)];
    [scrollview addGestureRecognizer:myTap];
    NSArray *titleAry = @[@"手机",@"密码",@"验证码",@"邀请码"];
    NSArray *imgAry = @[@"logphone",@"logPassw",@"codeimg",@"yaoqinma"];
    NSArray *pladerAry = @[@"在这里输入手机号",@"请输入密码",@"请输入验证码",@"请输入邀请码"];
    for (int i = 0; i < titleAry.count; i ++)
    {
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(35*displaywidth,65*displaywidth+95*displaywidth*i,20*displaywidth,25*displaywidth) ImageName:imgAry[i]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [scrollview addSubview:imgView];
        UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 65*displaywidth+95*displaywidth*i, 70*displaywidth, 25*displaywidth) Font:13.0 Text:titleAry[i] Color:RGB(77, 77, 77)];
        [scrollview addSubview:titLab];
        UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(50*displaywidth, 100*displaywidth+95*displaywidth*i, SCREEN_WIDTH-100*displaywidth, 30*displaywidth) placeholder:pladerAry[i] passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
        [textfield setValue:RGB(179, 179, 179) forKeyPath:@"_placeholderLabel.textColor"];
        textfield.textColor = RGB(77, 77, 77);
        textfield.delegate = self;
        [scrollview addSubview:textfield];
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(35*displaywidth, 140*displaywidth+95*displaywidth*i, SCREEN_WIDTH-70*displaywidth, 1*displaywidth)];
        line.backgroundColor = LinesColor;
        [scrollview addSubview:line];
        if (i == 0)
        {
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            phoneField = textfield;
        }
        else if (i == 1)
        {
            textfield.secureTextEntry = YES;
            passwordField = textfield;
        }
        else if (i == 2)
        {
            textfield.keyboardType = UIKeyboardTypeNumberPad;
            textfield.frame = CGRectMake(50*displaywidth, 100*displaywidth+95*displaywidth*i, 120*displaywidth, 30*displaywidth);
            codeField = textfield;
            codeBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-160*displaywidth, 100*displaywidth+95*displaywidth*i, 120*displaywidth, 30*displaywidth) ImageName:nil Target:self Action:@selector(verifiBtnAction:) Title:@"获取验证码" Font:13.0];
            [codeBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
            codeBtn.backgroundColor = [UIColor whiteColor];
            [codeBtn.layer setCornerRadius:15*displaywidth];
            [codeBtn.layer setMasksToBounds:YES];
            codeBtn.layer.borderColor = ThemeColor.CGColor;
            codeBtn.layer.borderWidth = 1*displaywidth;
            [scrollview addSubview:codeBtn];
        }
        else
        {
            invitField = textfield;
        }
    }
    UIImageView *closeCityView = [ZCControl createImageViewWithFrame:CGRectMake(35*displaywidth,455*displaywidth,20*displaywidth,25*displaywidth) ImageName:@"prives"];
    closeCityView.contentMode = UIViewContentModeScaleAspectFit;
    [scrollview addSubview:closeCityView];
    UIButton *cityBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    cityBtn.backgroundColor =[UIColor clearColor];
    cityBtn.frame = CGRectMake(65*displaywidth,455*displaywidth,80*displaywidth,25*displaywidth);
    [cityBtn setImage:[UIImage imageNamed:@"showcity"] forState:UIControlStateNormal];
    cityBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [cityBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
    [cityBtn setTitle:@" 省市" forState:UIControlStateNormal];
    [cityBtn addTarget:self action:@selector(choosetimeBtnAct) forControlEvents:UIControlEventTouchUpInside];
    CGSize imgSize = cityBtn.currentImage.size;
    CGSize titleSize = [cityBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:cityBtn.titleLabel.font}];
    UIEdgeInsets   titleEdgeInsets = UIEdgeInsetsMake(0, -imgSize.width-5, 0, imgSize.width+5);
    UIEdgeInsets imgEdgeInsets = UIEdgeInsetsMake(0, 5+titleSize.width, 0, -titleSize.width-5);
    cityBtn.titleEdgeInsets = titleEdgeInsets;
    cityBtn.imageEdgeInsets = imgEdgeInsets;
    cityBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    cityBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [scrollview addSubview:cityBtn];
    
    cityLab = [ZCControl createLabelWithFrame:CGRectMake(50*displaywidth, 480*displaywidth, SCREEN_WIDTH-100*displaywidth, 30*displaywidth) Font:13.0 Text:@"" Color:RGB(77, 77, 77)];
    [scrollview addSubview:cityLab];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(35*displaywidth, 520*displaywidth, SCREEN_WIDTH-70*displaywidth, 1*displaywidth)];
    line.backgroundColor = LinesColor;
    [scrollview addSubview:line];
    
}

- (void)choosetimeBtnAct
{
    CloseAreaViewController *vc= [[CloseAreaViewController alloc] init];
    WEAKSELF;
    vc.chooseblock = ^(AddressModel *priveModel, AddressModel *cityModel, AddressModel *areaModel)
    {
        weakSelf.provceModel = priveModel;
        weakSelf.cityModel = cityModel;
        weakSelf.areasModel = areaModel;
        dispatch_async(dispatch_get_main_queue(), ^{
            cityLab.text = [NSString stringWithFormat:@"%@-%@-%@",priveModel.name,cityModel.name,areaModel.name];
            
        });
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)verifiBtnAction:(UIButton *)btn
{
    if (phoneField.text.length < 1)
    {
        [LTools showMBProgressWithText:@"请输入手机号" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入正确的手机号" addToView:self.view];
        return;
    }
    [self requestRegisCode4register];
    
}

//注册验证码
- (void)requestRegisCode4register
{
    [self.view endEditing:YES];
    WEAKSELF;
    NSDictionary *dic = @{@"phone":phoneField.text,
                          @"type":@"1"
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestCodeRegisterParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             [LTools showMBProgressWithText:@"验证码已发送" addToView:weakSelf.view];
             [weakSelf startTimer];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

//注册
- (void)receiveRecord
{
    [self.view endEditing:YES];
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入手机号码" addToView:self.view];
        return;
    }
    if ([passwordField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请设置密码" addToView:self.view];
        return;
    }
    if ([codeField.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请输入验证码" addToView:self.view];
        return;
    }
    NSString *intaveStr = invitField.text;
    if (intaveStr.length == 0)
    {
        intaveStr = _keyStr;
    }
    if ([cityLab.text isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"请选择省市" addToView:self.view];
        return;
    }
    [self requestPublicKey:passwordField.text IntaveStr:intaveStr];
}

- (void)requestPublicKey:(NSString *)passWorld IntaveStr:(NSString *)intaveStr
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:sharedDelegate.window animated:YES];
    [HYBaseHandler requestPublicKeyParmers:nil Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             NSString *publicKey = obj[@"data"];
             //测试要加密的数据
             NSString *sourceStr = passWorld;
             //公钥加密
             NSString *encryptStr = [RSA encryptString:sourceStr publicKey:publicKey];
             NSDictionary *dic = @{@"cityId":_cityModel.ID,
                                   @"cityText":_cityModel.name,
                                   @"inviteCode":intaveStr,
                                   @"msgCode":codeField.text,
                                   @"password":encryptStr,
                                   @"phone":phoneField.text,
                                   @"provinceId":_provceModel.ID,
                                   @"provinceText":_provceModel.name,
                                   @"districtId":_areasModel.ID,
                                   @"districtText":_areasModel.name
                                   };
             [self requestRegisterParmers:dic];
             
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
             [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
     }];
}


- (void)requestRegisterParmers:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestRegisterParmers:dic Success:^(id obj)
    {
        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];
        if ([obj server_Getcodecheck])
        {
            NSString *token = obj[@"data"][@"token"];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"provinceId"]] ForKey:SERVER_sheng];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"cityId"]] ForKey:SERVER_shi];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"districtId"]] ForKey:SERVER_qu];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"provinceText"]] ForKey:SERVER_shengName];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"cityText"]] ForKey:SERVER_shiName];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"districtText"]] ForKey:SERVER_quName];
            [LTools cache:[NSString stringWithFormat:@"%@",obj[@"data"][@"id"]] ForKey:SERVER_UserID];
            [LTools cache:obj[@"data"][@"phone"] ForKey:SERVER_Phone];
            [LTools storage:YES ForKey:SERVER_IsLogin];
            [LTools cache:token ForKey:SERVER_LoginToken];
            [LTools showMBProgressWithText:@"注册成功" addToView:sharedDelegate.window];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];

        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        
    } failed:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:sharedDelegate.window animated:YES];

    }];
}

- (void)requestFindByKey
{
    WEAKSELF;
    NSDictionary *dic = @{@"key":@"default_recommend_code"};
    [HYBaseHandler requestFindByKeyParmers:dic Success:^(id obj)
     {
         if ([obj server_Getcodecheck])
         {
             NSString *key = obj[@"data"][@"propertyValue"];
             weakSelf.keyStr = s_str(key);
             invitField.text = s_str(key);
             
         }
         else
         {
             weakSelf.keyStr = @"15821105440";
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
         
     } failed:^(NSError *error) {
         
     }];
}


- (void)startTimer
{
    seconds = 60;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(calculateTime) userInfo:Nil repeats:YES];
    codeBtn.userInteractionEnabled = NO;
}
//计算时间
- (void)calculateTime
{
    NSString *title = [NSString stringWithFormat:@"(%dS)重新获取",seconds];
    codeBtn.titleLabel.text = title;
    [codeBtn setTitle:title forState:UIControlStateNormal];
    
    if (seconds != 0) {
        seconds --;
    }else
    {
        [self renewTimer];
    }
    
}
//计时器归零
- (void)renewTimer
{
    [timer invalidate];//计时器停止
    codeBtn.userInteractionEnabled = YES;
    [codeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
    seconds = 60;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField != phoneField && textField != passwordField)
    {
        scrollview.frame = CGRectMake(0, -160*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT);

    }
}

- (void)scrollTap:(id)sender
{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView*)scrollView
{
    [self.view endEditing:YES];
}

- (void)jianpanhuishou:(NSNotification *)notification
{
    scrollview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
